﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using You2V.Data.Shared;
using You2V.Data;
using System.Data;
using You2V.LocalDBLayer;

namespace You2VTool.Controls
{
    /// <summary>
    /// Interaction logic for StudentAction.xaml
    /// </summary>
    public partial class StudentAction : UserControl
    {
        public StudentAction()
        {
            InitializeComponent();
			formatGrid();
        }

        public void ReLocateStudent(Student student)
        {
			source = student;
			this.DataContext = student;
            windowsFormat();
        }

        private Student source;
        private void windowsFormat()
        {
            if (source == null)
                return;

            //建议显示改成对外的编号如MS12001，如有问题请和我讨论 (by Gang Cheng)
            //tb_stuID.Text = source.tc_id.ToString();
            tb_stuID.Text = source.StudentNumber;

            tb_name.Text = source.FullName;
            combobox_Status.DataContext = You2VDataDictionary.SponsorShipTrackingList;

            if (source.tc_info != null)
            {
                combobox_Status.SelectedValue = source.tc_info.SponsorShipTracking;
            }


			try
			{
				bool _cleanup = (source.tc_currentEduInfo == null);
				formatMainTextBox(_cleanup);
				this.formatSponsor(_cleanup);
				this.formatPeriod(_cleanup);
			}
			catch (ObjectNotFoundException ex)
			{
				MessageBox.Show(ex.Message);
			}
        }
		private void formatMainTextBox(bool clean)
		{
			if (clean)
			{
				tb_school.Text = "";
				tb_class.Text = "";
				tb_amount.Text = "";
				tb_volunteer.Text = "";
				tb_contact.Text = "";
				tb_teacher.Text = "";
			}
			else
			{
				tb_school.Text = source.tc_currentEduInfo.schoolName;
				tb_class.Text = source.tc_currentEduInfo.className;
				tb_amount.Text = source.tc_currentEduInfo.amount;
				tb_volunteer.Text = source.tc_currentEduInfo.volunteer;
				tb_contact.Text = source.tc_currentEduInfo.contact;
				tb_teacher.Text = source.tc_currentEduInfo.teacher;
			}
		}
		private void formatSponsor(bool clean)
		{
			List<Sponsor> p_list = new List<Sponsor>();
			if ((!clean) && source.tc_sponsor != null)
				p_list.Add(source.tc_sponsor);
			dg_Sponsor.ItemsSource = p_list;
		}
		private void formatPeriod(bool clean)
		{
			if (!clean)
			{
				cb_period.ItemsSource = source.tc_period.ValidPeriod;
				cb_period.SelectedIndex = 0;
                ActionDatePicker.SelectedDate = DateTime.Today;
				bindingPeriodAction();
			}
			else
			{
				cb_period.ItemsSource = null;
			}
		}
		private void bindingPeriodAction()
		{
			if (cb_period.SelectedItem != null)
			{
				string _selectedPeriod = cb_period.SelectedItem.ToString();
				DataTable _resource = source.tc_period.GetPeriodDataGrid(_selectedPeriod);
				dg_periodAction.ItemsSource = _resource.DefaultView;
			}
		}
		private void formatGrid()
		{
			DataTable _resource = StudentPeriodCollection.GetPeriodTable();
			foreach (DataColumn p_r in _resource.Columns)
			{
				if (p_r.ColumnName != "periodActionSummary")
				{
					DataGridTextColumn p_column = new DataGridTextColumn();
					p_column.Header = p_r.ColumnName;
					//p_column.MinWidth = 60;

					Binding binding = new Binding(p_r.ColumnName);
					p_column.Binding = binding;
					dg_periodAction.Columns.Add(p_column);
				}
			}

			cb_periodAction.ItemsSource = You2VDataDictionary.GetStudentAvaliableActionList();
			cb_periodAction.SelectedIndex = 0;
		}

        private void saveNewStudentEduInfo()
		{
			if (source.UpdateEduInfo(tb_school.Text, tb_class.Text
				, tb_amount.Text, tb_volunteer.Text, tb_contact.Text, tb_teacher.Text))
				MessageBox.Show("该学生的新联系方式已经保存");

            SaveSponsorShipTracking();  //暂时放到这里保存， TODO

			
		}
		private void saveStudentActionInfo()
		{
			int _amount = 0;
			try
			{
				_amount = Convert.ToInt32(tb_actionAmount.Text);
			}
			catch
			{
				MessageBox.Show("请在金额中输入正确的数字，不要有小数点", "信息不完整");
				return;
			}

			if (cb_periodActionAdd.IsChecked ?? true)
			{
				DateTime ActionTime = DateTime.Today;

				if (ActionDatePicker.SelectedDate != null)
				{
					ActionTime = (DateTime)ActionDatePicker.SelectedDate;
				}

				source.AddNewPeriodAction(cb_period.SelectedItem.ToString(),
					cb_periodAction.SelectedItem.ToString(),
					_amount,
					tb_actionDescription.Text,
					ActionTime);
			}
			if (cb_periodActionDelete.IsChecked ?? true)
			{
				source.DisablePeriodAction((Guid)cb_perioddeletedAction.SelectedValue, tb_actionDescription.Text);
			}
			bindingPeriodAction();
		}
        private void SaveSponsorShipTracking()
        {
            //直接存入数据库
            string CurrentStatus = (string)combobox_Status.SelectedValue;

            if (!string.IsNullOrWhiteSpace(CurrentStatus))
            {
                if (source != null && source.tc_info != null)
                {
                    source.tc_info.SponsorShipTracking = CurrentStatus; //必须更新，否则DataGrid中对应的数据就是旧的了
                    string SQLCommand = "UPDATE Student2012 SET SponsorShipTracking = '" + CurrentStatus + "' WHERE ID={" + source.tc_info.ID + "}";
                    if (!DBAccess.RunCommand(SQLCommand))
                    {
                        MessageBox.Show("无法更新数据库, 错误编号 22259");
                        return;
                    }
                }
            }
        }
		private void editActionShowCase()
		{
			if (cb_periodActionAdd.IsChecked ?? true)
			{
				string _action = cb_periodAction.SelectedItem.ToString();
				if (StudentActionEnum.items[_action].ShowAccount)
				{
					dock_add.Visibility = System.Windows.Visibility.Visible;
					dock_add.Height = 30;
				}
				else
				{
					dock_add.Visibility = System.Windows.Visibility.Hidden;
					dock_add.Height = 0;
				}
				dock_disable.Visibility = System.Windows.Visibility.Hidden;
				dock_disable.Height = 0;
			}
			else
			{
				if (cb_period.SelectedItem != null)
				{
					string _selectedPeriod = cb_period.SelectedItem.ToString();
					cb_perioddeletedAction.ItemsSource = source.tc_period.Items[_selectedPeriod].periodActions;
					cb_perioddeletedAction.DisplayMemberPath = "Agenda";
					cb_perioddeletedAction.SelectedValuePath = "ID";
					cb_perioddeletedAction.SelectedIndex = 0;

				}
				dock_add.Visibility = System.Windows.Visibility.Hidden;
				dock_disable.Visibility = System.Windows.Visibility.Visible;
				dock_add.Height = 0;
				dock_disable.Height = 30;
			}

			tb_actionAmount.Text = "0";
			tb_actionDescription.Text = "";
		}

		#region Event
		private void bt_saveEduInfo_Click(object sender, RoutedEventArgs e)
		{
			if (source == null)
			{
				MessageBox.Show("请在左侧列表选择一个学生");
				return;
			}
			saveNewStudentEduInfo();
		}

		private void cb_periodAction_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			editActionShowCase();
		}

		private void bt_saveAction_Click(object sender, RoutedEventArgs e)
		{
			if (source == null)
			{
				MessageBox.Show("请在左侧列表选择一个学生");
				return;
			}
			saveNewStudentEduInfo();
			saveStudentActionInfo();
		}

		private void cb_period_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			bindingPeriodAction();
		}

		private void cb_periodActionAdd_Checked(object sender, RoutedEventArgs e)
		{
			if (dock_add != null)
			{
				editActionShowCase();
			}
		}

		private void cb_periodActionDelete_Checked(object sender, RoutedEventArgs e)
		{
			editActionShowCase();
		}
		#endregion
	}
}
